<?php

namespace app\admin\controller;

use app\admin\validate\SGoods as SGoodsValidate;
use app\common\business\SGoods as SGoodsBus;
use app\common\lib\Check;
use app\common\lib\toCamelCase;
use app\common\model\mysql\SGoodsCategory;
use app\common\model\mysql\SGoodsImage;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\facade\Db;

class SGoods extends AuthBase
{
    //轮播图选择商品链接列表
    public function goodsChooseList(){
        $where = [];
        // 获取分页参数
        $page = $this->request->param('pageNum', 1);
        $limit = $this->request->param('pageSize', 10);
        $goodsName = $this->request->param('goodsName',"");
        $goodsField = $this->request->param('goodsField',"");
        if($goodsName){
            $where[] = ['goods_name', 'like', '%'.$goodsName.'%'];
        }
        $where[] = ['goods_type','=', 0];
        $where[] = ['del_flag', '=', '0'];
        try {
            $goodsData = (new SGoodsBus())->getNormalGoodsData($where,$goodsField,$limit,$page);
            $goodsData = (new toCamelCase())->toCamelCaseArray($goodsData);
            if($goodsData['data']){
                foreach ($goodsData['data'] as &$goodsItem) {
                    $goodsItem['url'] = '/pages/goods/goods/index?id='.$goodsItem['id'];
                }
            }
        }catch (\Exception $e){
            $goodsData = [];
        }
        return show(config("status.success"), "轮播图选择商品链接列表", $goodsData);
    }

    //获取商品数据列表查询条件
    public function goodsListSearch(){
        $where = [];
        // 获取分页参数
        $page = $this->request->param('pageNum', 1);
        $limit = $this->request->param('pageSize', 10);
        $goodsName = $this->request->param('goodsName',"");
        $categoryId = $this->request->param('categoryId',"");
        $goodsField = $this->request->param('goodsField',"");
        if($goodsName){
            $where[] = ['goods_name', 'like', '%'.$goodsName.'%'];
        }
        if($categoryId){
            $map[] = ['category_id', '=', $categoryId];
            $goodsId = (new SGoodsBus())->getNormalGoodsFieldData($map,'goods_id');
            if($goodsId){
                $where[] = ['goods_id', 'in', $goodsId];
            }else{
                return [
                    'page'=>$page,
                    'limit'=>$limit,
                    'where'=>$where,
                    'isGoods'=>false,
                    'goodsField'=>$goodsField,
                ];
            }
        }
        $where[] = ['goods_type','=', 0];
        $where[] = ['del_flag', '=', '0'];
        return [
            'page'=>$page,
            'limit'=>$limit,
            'where'=>$where,
            'isGoods'=>true,
            'goodsField'=>$goodsField,
        ];
    }

    // 处理商品分类信息
    private function processCategories(&$goodsData)
    {
        foreach ($goodsData as &$goodsItem) {
            if (isset($goodsItem['categorySelected']) && !empty($goodsItem['categorySelected'])) {
                $categoryIds = array_map(function ($subArray) {
                    return end($subArray); // 使用 end() 获取子数组的最后一个元素
                }, json_decode($goodsItem['categorySelected'], true));

                $goodsItem['categoryIds'] = $categoryIds;
                $goodsItem['categoryNames'] = (new \app\common\business\SCategory())->getCategoryByNames($categoryIds);
            } else {
                $goodsItem['categoryIds'] = [];
                $goodsItem['categoryNames'] = '';
            }
        }
    }

    //商品数据列表
    public function goodsList(){
        $searchData = $this->goodsListSearch();
        $configData = [];

        try {
            if ($searchData['isGoods']) {
                $goodsFields = $searchData['goodsField'] ?: '*';
                $configData = (new SGoodsBus())->getNormalGoodsData(
                    $searchData['where'],
                    $goodsFields,
                    $searchData['limit'],
                    $searchData['page']
                );

                if (!empty($configData['data'])) {
                    $configData = (new toCamelCase())->toCamelCaseArray($configData);
                    $this->processCategories($configData['data']);
                }
            }
        } catch (\Exception $e) {
            // 记录异常日志或执行其他错误处理逻辑
            // 例如：error_log($e->getMessage());
            // 根据需要抛出异常或返回错误响应
            return show(config("status.error"), $e->getMessage(), []);
        }
        return show(config("status.success"), "商品数据列表", $configData);
    }

    //商品添加
    public function goodsAdd(){
        if (!$this->request->isPost()){
            return show(config("status.error"),"请求方式错误");
        }
        //参数校验
        $allParams = request()->param();
        $data = (new toCamelCase())->toCamelCaseArray($allParams,'1',2);
        $validate = new SGoodsValidate();
        if(!$validate->check($data)){
            return show(config("status.error"),$validate->getError());
        }
        try {
            Db::startTrans(); // 开始事务
            if($data['logistics_mode']){
                $data['logistics_mode'] = implode(',',$data['logistics_mode']);
            }
            if($data['goods_recommend']){
                $flags = [
                    1 => 'is_hot',
                    2 => 'is_benefit',
                    3 => 'is_best',
                    4 => 'is_new',
                    5 => 'is_good'
                ];

                foreach ($data['goods_recommend'] as $item) {
                    if (isset($item) && array_key_exists($item, $flags)) {
                        $data[$flags[$item]] = 1;
                    }
                }
                $data['goods_recommend'] = implode(',',$data['goods_recommend']);
            }
            if($data['is_extension']){
                if (is_array($data['is_extension']) && in_array(1, $data['is_extension'])) {
                    // 如果 $data['is_extension'] 是一个数组，并且包含数字 1，则执行这里的代码
                    $data['is_extension'] = 1;
                    if($data['set_extension_data']){
                        $data['extension_one'] = $data['set_extension_data'][0]['firstLevelCommission'];
                        $data['extension_two'] = $data['set_extension_data'][0]['secondLevelCommission'];
                    }
                }
            }
            if($data['category_id']){
                $data['category_selected'] = json_encode($data['category_id']);
            }
            $result = (new SGoodsBus())->addGoods($data);
            if($result){
                if($data['category_id']){
                    $categoryIdsArr = [];
                    foreach ($data['category_id'] as $subArray) {
                        if (!empty($subArray)) {
                            $categoryIdsArr[] = end($subArray);
                        }
                    }
                    (new SGoodsCategory())->insertAllGoodsCategory($categoryIdsArr,$result);
                }
                if($data['goods_img']){
                    (new SGoodsImage())->insertAllGoodsImage($data['goods_img'],$result);
                }
            }
        }catch (\Exception $e){
            Db::rollback();
            return show(config('status.error'),$e->getMessage());
        }
        Db::commit();
        return show(config("status.success"),"新增成功",$result);
    }

    //商品修改
    public function goodsEdit(){
        $allParams = request()->param();
        $data = (new toCamelCase)->toCamelCaseArray($allParams,1,2);
        // 初始化事务
        Db::startTrans();
        try {
            if($data['logistics_mode']){
                $data['logistics_mode'] = implode(',',$data['logistics_mode']);
            }
            $data['is_hot'] = $data['is_benefit'] = $data['is_best'] = $data['is_new'] = $data['is_good'] = 0;
            if($data['goods_recommend']){
                $flags = [
                    1 => 'is_hot',
                    2 => 'is_benefit',
                    3 => 'is_best',
                    4 => 'is_new',
                    5 => 'is_good'
                ];

                foreach ($data['goods_recommend'] as $item) {
                    if (isset($item) && array_key_exists($item, $flags)) {
                        $data[$flags[$item]] = 1;
                    }
                }
                $data['goods_recommend'] = implode(',',$data['goods_recommend']);
            }
            if($data['category_id']){
                $data['category_selected'] = json_encode($data['category_id']);
            }
            if($data['is_extension']){
                if (is_array($data['is_extension']) && in_array(1, $data['is_extension'])) {
                    // 如果 $data['is_extension'] 是一个数组，并且包含数字 1，则执行这里的代码
                    $data['is_extension'] = 1;
                    if($data['set_extension_data']){
                        $data['extension_one'] = $data['set_extension_data'][0]['firstLevelCommission'];
                        $data['extension_two'] = $data['set_extension_data'][0]['secondLevelCommission'];
                    }
                }
            }else{
                $data['is_extension'] = 0;
                $data['extension_one'] = 0;
                $data['extension_two'] = 0;
            }
            $result = (new SGoodsBus())->updateById($data['goods_id'],$data);

            if ($result){
                (new SGoodsImage())->deleteImageIds($data['goods_id']);
                (new SGoodsCategory())->deleteCategoryIds($data['goods_id']);
                if($data['category_id']){
                    $categoryIdsArr = [];
                    foreach ($data['category_id'] as $subArray) {
                        if (!empty($subArray)) {
                            $categoryIdsArr[] = end($subArray);
                        }
                    }
                    (new SGoodsCategory())->insertAllGoodsCategory($categoryIdsArr,$data['goods_id']);
                }
                if($data['old_goods_img']){
                    $resultImg = (new SGoodsImage())->insertAllGoodsImage($data['old_goods_img'],$data['goods_id']);
                }
                if($data['goods_img']){
                    $resultImg = !empty($resultImg) ? $resultImg : 0;
                    (new SGoodsImage())->insertAllGoodsImage($data['goods_img'],$data['goods_id'],$resultImg);
                }
            }
        }catch (\Exception $e){
            Db::rollback();
            return show(config('status.error'),$e->getMessage());
        }
        Db::commit();
        return show(config("status.success"),"修改成功",$result);
    }

    //删除商品
    public function goodsDel(){
        $goodsId = $this->request->param("goodsId","","trim");
        if(empty($goodsId)){
            return show(config("status.error"),"参数不能为空");
        }
        try {
            $result = (new SGoodsBus())->delGoodsIds($goodsId);
        }catch (\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        return show(config("status.success"),"删除成功",$result);
    }

    //商品详情
    public function goodsDetails(){
        $goodsId = $this->request->param("goodsId","","trim");
        if(empty($goodsId)){
            return show(config("status.error"),"参数不能为空");
        }
        try {
            $roleData = (new SGoodsBus())->getGoodsById($goodsId);
            $roleData = (new toCamelCase())->toCamelCaseArray($roleData);
        }catch (\Exception $e){
            $roleData = [];
        }
        if($roleData['logisticsMode']){
            $roleData['logisticsMode'] = explode(',',$roleData['logisticsMode']);
            // 将数组中的每个元素从字符串转换为整数
            foreach ($roleData['logisticsMode'] as &$value) {
                $value = (int)$value;
            }
            unset($value);
        }else{
            $roleData['logisticsMode'] = [];
        }
        if($roleData['goodsRecommend']){
            $roleData['goodsRecommend'] = explode(',',$roleData['goodsRecommend']);
            // 将数组中的每个元素从字符串转换为整数
            foreach ($roleData['goodsRecommend'] as &$value) {
                $value = (int)$value;
            }
            unset($value);
        }else{
            $roleData['goodsRecommend'] = [];
        }
        $roleData['categorySelected'] = json_decode($roleData['categorySelected']);
        $getImagesArr = (new SGoodsImage())->getImages($goodsId);
        $roleData['goodsImg'] = $getImagesArr;
        if($roleData['isExtension'] == 1){
            $roleData['isExtension'] = [1];
            $roleData['setExtensionData'] = array(
              array(
                  'firstLevelCommission'=>$roleData['extensionOne'],
                  'secondLevelCommission'=>$roleData['extensionTwo'],
              ),
            );
        }else{
            $roleData['isExtension'] = [];
            $roleData['setExtensionData'] = array(
                array(
                    'firstLevelCommission'=>0,
                    'secondLevelCommission'=>0,
                ),
            );
        }
        return show(config("status.success"),"商品详情",$roleData);
    }

    //导出商品数据信息
    public function exportGoods(){
        $searchData = $this->goodsListSearch();
        if($searchData['isGoods']){
            $postCount = (new SGoodsBus())->getNormalGoodsCount($searchData['where']);
            $configData = (new SGoodsBus())->getNormalGoodsData($searchData['where'],'*',$postCount,$searchData['page']);
        }else{
            $configData['data'] = [];
        }
        // 创建Spreadsheet对象
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        $sheet->mergeCells('A1:G1'); // 假设表头只有5列
        $sheet->setCellValue('A1', '商品数据信息');
        // 设置表头
        $header = ['商品ID', '商品图', '商品名称', '商品类型', '商品售价','销量','库存量'];
        $row = 2;
        $col = 1; // 列索引，从A列开始
        foreach ($header as $column) {
            // 使用setCellValueByColumnAndRow时，第二个参数是列号（整数），第三个参数是值
            $sheet->setCellValueByColumnAndRow($col, $row, $column);
            $col++; // 移动到下一列
        }
        // 使用循环设置列宽
        $columns = ['A', 'B', 'C', 'D', 'E', 'F','G']; // 定义需要设置宽度的列
        foreach ($columns as $column) {
            $sheet->getColumnDimension($column)->setWidth(21);
        }
        // 填充数据
        $row = 3;
        foreach ($configData['data'] as $post) {
            $post['goods_type'] = "普通商品";
            $post['main_img_url'] = (new Check())->checkUrl($post['main_img_url']);
            $sheet->setCellValue('A' . $row, $post['goods_id']);
            $sheet->setCellValue('B' . $row, $post['main_img_url']);
            $sheet->setCellValue('C' . $row, $post['goods_name']);
            $sheet->setCellValue('D' . $row, $post['goods_type']);
            $sheet->setCellValue('E' . $row, $post['selling_price']);
            $sheet->setCellValue('F' . $row, $post['quantity_sold']);
            $sheet->setCellValue('G' . $row, $post['stock']);
            // 填充其他字段
            $row++;
        }
        $row = $row-1;
        $SpreadsheetObj = new \app\common\lib\Spreadsheet();
        $sheet->getStyle('A1')->applyFromArray($SpreadsheetObj->fontArray('FF000000',18));
        $sheet->getStyle('A2:G2')->applyFromArray($SpreadsheetObj->fillArray("808080"));
        $sheet->getStyle('A2:G2')->applyFromArray($SpreadsheetObj->fontArray("FFFFFFFF"));
        $sheet->getStyle('A1' . ':G' . $row)->applyFromArray($SpreadsheetObj->styleBorderArray());
        $sheet->getStyle('A1' . ':G' . $row)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);

        // 创建Writer对象，并保存为xlsx文件
        $writer = new Xlsx($spreadsheet);
        // 设置响应头
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="goods.xlsx"');
        header('Cache-Control: max-age=0');
        // 导出
        $writer->save('php://output');
        exit;
    }

    //上传商品轮播图
    public function addFileGoodsImgs(){
        $uploadedFiles = file::uploadFiles('images','goodsImg');
        return show(config("status.success"), "ok", $uploadedFiles);
    }

    //上传商品图片
    public function goodsUploadFile(){
        $imgUrl = file::uploadFile('file','goodsImg');
        return show(config("status.success"),"ok",$imgUrl);
    }

    //更改商品状态
    public function changeStatus(){
        $goodsId = $this->request->param("goodsId","","trim");
        $status = $this->request->param("status","","trim");
        // 验证 goodsId 是否存在
        if (empty($goodsId)) {
            return show(config("status.error"), "商品ID不能为空");
        }
        if ($status == "") {
            return show(config("status.error"), "用户状态不能为空");
        }
        try {
            $result = (new SGoodsBus())->changeStatusGoods($goodsId,$status);
        }catch (\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        return show(config("status.success"),"操作成功",$result);
    }
}
